package com.aide.simplification.global.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.aide.simplification.global.Utils;
import com.aide.simplification.popedom.login.LoginUser;
import com.aide.simplification.popedom.login.PopSSO;

public class ContextFilter extends HttpServlet implements Filter {
	private static final long serialVersionUID = -1902777340730364748L;
	private FilterConfig filterConfig;

	public void init(FilterConfig filterConfig) {
		this.filterConfig = filterConfig;
	}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain filterChain) {
		try {
			HttpServletRequest httpRequest = (HttpServletRequest) request;
			String path = httpRequest.getContextPath();
			String accessPath=httpRequest.getRequestURI();
			String[] noFilterStr = { "/index.jsp", "/timeout.jsp","/sso.jsp",
					"/piccheck.jsp", "/consttest.jsp", "/tagtest.jsp", "/configtest.jsp"};
			boolean flag = true;
			
			if (accessPath.indexOf(path + "/") == (accessPath.length()- path.length() - 1)) {
				flag = false;
			}
			for (int i = 0; i < noFilterStr.length; i++) {
				if (httpRequest.getRequestURL().indexOf(noFilterStr[i]) != -1) {
					flag = false;
					break;
				}
			}
			if (flag) {
				LoginUser lu = null;
				PopSSO popsso = new PopSSO(request, response);
				lu = popsso.ssoSync();
				if(lu==null){
					lu=popsso.checkURLParameter();
				}
				if (lu == null) {
					((HttpServletResponse) response).sendRedirect(Utils.getConfig("pop.path")+ Utils.getConfig("pop.timeout_page")+"?url="+accessPath);
				} else {
						filterChain.doFilter(request, response);
					
				}
			} else {
				filterChain.doFilter(request, response);
			}
		} catch (ServletException sx) {
			filterConfig.getServletContext().log(sx.getMessage());
		} catch (IOException iox) {
			filterConfig.getServletContext().log(iox.getMessage());
		}
	}

	// Clean up resources
	public void destroy() {

	}
}